/**
 * 全局npm包配置入口
 * 统一管理项目中使用的npm包，便于更换路径和提供降级实现
 */

// 优先确保process对象存在
(function ensureProcess() {
  // 安全获取全局对象
  function getGlobalObject() {
    if (typeof globalThis !== 'undefined') return globalThis;
    if (typeof global !== 'undefined') return global;
    if (typeof window !== 'undefined') return window;
    if (typeof self !== 'undefined') return self;
    return {};
  }
  
  const globalObj = getGlobalObject();
  
  // 确保process对象存在
  if (typeof globalObj.process === 'undefined') {
    globalObj.process = { env: { NODE_ENV: 'production' } };
    try { process = globalObj.process; } catch (e) {}
  }
})();

// 加载MobX polyfill
try {
  require('../helpers/mobx_polyfill.js');
} catch (e) {
  console.warn('[npm_config] 无法加载MobX polyfill:', e);
}

// 预先加载libs_config确保MobX库正确加载
const libsConfig = require('./libs_config.js');

/**
 * 导入MobX包
 */
let mobx, mobxMiniprogram, mobxBindings, dayjs;

// 从libs_config导入MobX
try {
  mobx = libsConfig.mobx;
  mobxMiniprogram = libsConfig.mobxMiniprogram;
  mobxBindings = {
    createStoreBindings: libsConfig.createStoreBindings,
    storeBindingsBehavior: libsConfig.storeBindingsBehavior
  };
} catch (error) {
  console.error('[npm_config] 从libs_config导入MobX失败，使用直接导入:', error);
  
  // 如果从libs_config导入失败，尝试直接导入
  try {
    mobx = require('../miniprogram_npm/mobx/patched.js');
  } catch (e1) {
    try {
      mobx = require('../miniprogram_npm/mobx/index.js');
    } catch (e2) {
      console.error('[npm_config] 加载mobx失败:', e2);
      // 提供最小化兼容对象
      mobx = {
        observable: (obj) => obj,
        action: (fn) => fn,
        configure: () => {},
        computed: (fn) => fn,
        autorun: (fn) => { fn(); return () => {}; }
      };
    }
  }
  
  try {
    mobxMiniprogram = require('../miniprogram_npm/mobx-miniprogram/patched.js');
  } catch (e1) {
    try {
      mobxMiniprogram = require('../miniprogram_npm/mobx-miniprogram/index.js');
    } catch (e2) {
      console.error('[npm_config] 加载mobx-miniprogram失败:', e2);
      // 提供最小化兼容对象
      mobxMiniprogram = {
        observable: mobx.observable,
        action: mobx.action,
        computed: mobx.computed
      };
    }
  }
  
  // 安全导入mobx绑定包
  try {
    const bindings = require('../miniprogram_npm/mobx-miniprogram-bindings/patched.js');
    mobxBindings = {
      createStoreBindings: bindings.createStoreBindings,
      storeBindingsBehavior: bindings.storeBindingsBehavior
    };
  } catch (e1) {
    try {
      const bindings = require('../miniprogram_npm/mobx-miniprogram-bindings/index.js');
      mobxBindings = {
        createStoreBindings: bindings.createStoreBindings,
        storeBindingsBehavior: bindings.storeBindingsBehavior
      };
    } catch (e2) {
      console.error('[npm_config] 加载mobx-miniprogram-bindings失败:', e2);
      // 提供最小化兼容对象
      mobxBindings = {
        createStoreBindings: (context, options) => {
          console.warn('[npm_config] 使用兼容版createStoreBindings');
          return {
            updateStoreBindings: () => {},
            destroyStoreBindings: () => {}
          };
        },
        storeBindingsBehavior: Behavior({})
      };
    }
  }
}

// 安全导入dayjs
try {
  dayjs = libsConfig.dayjs;
} catch (e1) {
  try {
    dayjs = require('../miniprogram_npm/dayjs/index.js');
  } catch (e2) {
    console.error('[npm_config] 加载dayjs失败:', e2);
    // 提供最小化兼容对象
    dayjs = (date) => {
      const d = date ? new Date(date) : new Date();
      
      return {
        format: (pattern) => {
          const year = d.getFullYear();
          const month = String(d.getMonth() + 1).padStart(2, '0');
          const day = String(d.getDate()).padStart(2, '0');
          const hours = String(d.getHours()).padStart(2, '0');
          const minutes = String(d.getMinutes()).padStart(2, '0');
          const seconds = String(d.getSeconds()).padStart(2, '0');
          
          return pattern
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', hours)
            .replace('mm', minutes)
            .replace('ss', seconds);
        },
        valueOf: () => d.getTime(),
        toDate: () => d,
        add: (value, unit) => {
          const newDate = new Date(d.getTime());
          
          switch (unit) {
            case 'year':
            case 'years':
              newDate.setFullYear(newDate.getFullYear() + value);
              break;
            case 'month':
            case 'months':
              newDate.setMonth(newDate.getMonth() + value);
              break;
            case 'day':
            case 'days':
              newDate.setDate(newDate.getDate() + value);
              break;
            case 'hour':
            case 'hours':
              newDate.setHours(newDate.getHours() + value);
              break;
            case 'minute':
            case 'minutes':
              newDate.setMinutes(newDate.getMinutes() + value);
              break;
            case 'second':
            case 'seconds':
              newDate.setSeconds(newDate.getSeconds() + value);
              break;
          }
          
          return dayjs(newDate);
        },
        subtract: (value, unit) => {
          return dayjs(d).add(-value, unit);
        },
        isValid: () => !isNaN(d.getTime())
      };
    };
    
    // 添加常用的静态方法
    dayjs.unix = (timestamp) => dayjs(timestamp * 1000);
    dayjs.utc = (date) => dayjs(date);
  }
}

// 导出包
module.exports = {
  // MobX相关
  mobx,
  mobxMiniprogram,
  observable: mobxMiniprogram.observable || mobx.observable,
  action: mobxMiniprogram.action || mobx.action,
  computed: mobxMiniprogram.computed || mobx.computed,
  autorun: mobx.autorun,
  
  // MobX绑定相关
  mobxBindings,
  createStoreBindings: mobxBindings.createStoreBindings,
  storeBindingsBehavior: mobxBindings.storeBindingsBehavior,
  
  // 日期处理
  dayjs,
  
  // 库路径解析
  getNpmPath: function(packageName) {
    return `../miniprogram_npm/${packageName}`;
  }
}; 